package com.qfedu.interceptor;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
@Controller
public class LogInterceptor implements HandlerInterceptor {

    // 得到log
    private static Logger logger = Logger.getLogger(LogInterceptor.class);

    // 为每一个线程分配的空间 /没调用一次处理器 都开辟一个线程
    ThreadLocal<Long> threadLocalTime = new ThreadLocal<>();

    @Override  // 在请求之前 调用
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();

        Map<String, String[]> map = request.getParameterMap();
        StringBuilder stringBuilder = new StringBuilder("?params:");
        for (String key :map.keySet()){
            stringBuilder.append(key+"=");
            String[] values =   map.get(key);
            for (String str:values){
                stringBuilder.append(str);
            }
            stringBuilder.append("&");
        }
        // System.out.println("url:"+url+stringBuilder.toString());
//        logger.info("url:"+url+stringBuilder.toString());
        //在请求之前保存时间戳到到当前线程
        threadLocalTime.set(System.currentTimeMillis());
        logger.info("ip:"+request.getRemoteAddr()+"sessionid"+request.getSession().getId());
        //获取所有参数
//        logger.info("param:"+request.getParameterMap());
        // 获取请求路径
        logger.info("url:"+request.getRequestURI()+stringBuilder.toString());
        // 放弃拦截
        return true;
    }

    @Override// 在处理器完成之后调用
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {


        long endTime = System.currentTimeMillis();

        // 获取当前线程的 访问preHandle 的时间
        long startTime = threadLocalTime.get();
        // 可以统计接口响应是时间  可以优化代码
        logger.info("url:"+request.getRequestURI()+"--userTime:"+(endTime-startTime));
    }

    @Override// 在整个请求完成之后调用
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
